<?php
/*
This class is written by Najeeb Ahmad on 4, Oct 2009. This will act interface between main db class (database_class.php) and front end application
*/


require('database_class.php');


class DBManager{

// Member variabels

// These variables are for signup 
	private $invitedBy;
	private $isAuthorized;
	
// Gloabl Settings 	
	private $totalRank;
	private $featuredStoreLimit;
	private $featuredItemLimit = 20;	
	
	var $totalRecords = 0;
	
	
	private $db;
	
	var $showQuery;
	var $exitScript;						//These both are related to show the query and exit if set to true;
	
	//Some settings can be here
	function __construct($pShowQuery=false, $pExitScript=false)
	{
		$this->db = new database();
		
		$this->showQuery = $pShowQuery;
		$this->exitScript = $pExitScript;
		
	}
	
	function __desctruct()
	{
		$this->db->close();
	}
//GETS========================================================================================================================GETS
	public function getError()
	{
		return $this->db->getMysqlError();
	}
	
	
	public function getSingleData($pTableName, $pColName, $pCriteria = "1 = 1")
	{
		$sql = 	"SELECT ".$pColName."
				FROM `".$pTableName."`
				WHERE ".$pCriteria."";
				
		$this->db->setQuery($sql, 'getSingleData');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		$row = $this->db->fetch_array(1);
		//print_r($row);
		
		return $row[$pColName];
	}
	
	public function incrementData($pTable, $pField, $pCriteria)	//$Field;Value style
	{
		$v = $this->getSingleData($pTable, $pField, $pCriteria);
		
		$v += 1;
		
		$sql = "UPDATE $pTable SET $pField = $v WHERE ".$pCriteria;
		
		$this->db->setQuery($sql, 'incrementData '.$pTable);
			
		if($this->showQuery) 
			$this->printQuery();
				
		if($this->db->executeQuery())
			return true;
		else
			return false;
	
	}

	public function getTotalRecords($pTableName, $pColName, $pCriteria = "1 = 1")
	{
		$sql = 	"SELECT ".$pColName."
				FROM `".$pTableName."`
				WHERE ".$pCriteria."";
				
		$this->db->setQuery($sql, 'getTotalRecords');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return count($tempArray);
	}
	
	
	public function getRowData($pTableName, $pColsName, $pCriteria = "1 = 1")
	{
		$sql = 	"SELECT ".$pColsName."
				FROM `".$pTableName."`
				WHERE ".$pCriteria."";
				
		$this->db->setQuery($sql, 'getData from Table '.$pTableName);
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$row  = $this->db->fetch_row();
		//print_r($row);
		return $row;
	}
	
	public function getArrayData($pTableName, $pColsName, $pCriteria = "1 = 1")
	{
		$sql = 	"SELECT ".mysql_real_escape_string(trim($pColsName))."
				FROM `".$pTableName."`
				WHERE ".$pCriteria."";
				
		$this->db->setQuery($sql, 'getData from Table '.$pTableName);
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
	}


	public function getAllMembers($pPage, $pType = null, $sort = null)
	{
		switch($sort)
		{
			case 'name':
				$orderby = 'ORDER BY FIRSTNAME ASC';
			break;
			
			case 'date':
			 	$orderby = 'ORDER BY REGISTEREDON ASC';
			break;
			
			case 'email':
				$orderby = 'ORDER BY EMAIL ASC';
			break;
			
			default:
				$orderby = 'ORDER BY FIRSTNAME ASC';
			break;
		}
		
		//$sql = 	$this->QM_select("members_tbl","*", 1,1);
		if($pType):
			$this->totalRecords = $this->getSingleData('members_tbl','COUNT(*)', "MEMBERTYPE = '$pType'");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM members_tbl WHERE MEMBERTYPE = '$pType'
					$orderby
					LIMIT $start, $limit";
		else:
			$this->totalRecords = $this->getSingleData('members_tbl','COUNT(*)');
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM members_tbl $orderby
					LIMIT $start, $limit";
		endif;
					
				
		$this->db->setQuery(htmlentities($sql), 'getAllMembers');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
	
		return $tempArray;
		
	}
	
	
	public function getStoreFeedback($pPage, $pStoreID, $pFilter = null)
	{
		//$sql = 	$this->QM_select("members_tbl","*", 1,1);
		if($pFilter):
			$this->totalRecords = $this->getTotalRecords('feedbacks_tbl','ID', "COMMENTLEVEL = ".CN_S($pFilter)." AND STOREID = ".CN_S($pStoreID));
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM feedbacks_tbl 
					WHERE STOREID = $pStoreID
					AND COMMENTLEVEL = '$pFilter'
					ORDER BY COMMENTEDON DESC
					LIMIT $start, $limit";
		else:
			$this->totalRecords = $this->getTotalRecords('feedbacks_tbl','ID',"STOREID = ".CN_S($pStoreID));
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM feedbacks_tbl 
					WHERE STOREID = $pStoreID
					ORDER BY COMMENTEDON DESC
					LIMIT $start, $limit";
		endif;
					
				
		$this->db->setQuery(htmlentities($sql), 'getStoreFeeback');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
				return $tempArray;
		
	}
	
	
	public function isFeedbackGiven($pOrderNumber, $pMemberID)
	{
		$row = $this->getRowData('feedbacks_tbl', '*', "ORDERNUMBER = '$pOrderNumber' AND GIVENBY = $pMemberID");
		
		return $row;
	}
	

	
	public function getAllBuyerOrders($pPage, $pOrderStatus = null)
	{
		if($pOrderStatus == null):
		$this->totalRecords = $this->getSingleData('orders_tbl','COUNT(*)');
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
		$sql = "SELECT O.ORDERNUMBER, O.ORDERDATE, O.ORDERSTATUS, O.STOREID, O.AMOUNTPAID, M.FIRSTNAME, M.LASTNAME, 
				M.COUNTRYNAME, M.CITY, M.ADDRESS, M.ADDRESS2, M.ZIPCODE, M.STATENAME, M.PROVINCE, M.PHONENUMBER
				FROM (
				orders_tbl O
				JOIN members_tbl M ON (
				O.BUYERID = M.ID))
				LIMIT $start, $limit";
		else:
		$this->totalRecords = $this->getSingleData('orders_tbl','COUNT(*)', "ORDERSTATUS = '$pOrderStatus'");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
		$sql = "SELECT O.ORDERNUMBER, O.ORDERDATE, O.ORDERSTATUS, O.STOREID, O.AMOUNTPAID, M.FIRSTNAME, M.LASTNAME, 
				M.COUNTRYNAME, M.CITY, M.ADDRESS, M.ADDRESS2, M.ZIPCODE, M.STATENAME, M.PROVINCE, M.PHONENUMBER
				FROM (
				orders_tbl O
				JOIN members_tbl M ON (
				O.BUYERID = M.ID))
				WHERE O.ORDERSTATUS = '$pOrderStatus'
				LIMIT $start, $limit";
		endif;

		$this->db->setQuery(htmlentities($sql), 'getAllBuyerOrders');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getMemberProfile($pMemID = null)
	{
		if($pMemID == null)
			$pMemID = $_COOKIE[memberid];
			
		$sql = 	$this->QM_select("members_tbl","*", 'ID', $pMemID);
				
		$this->db->setQuery(htmlentities($sql), 'getMemberProfile');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempRow = $this->db->fetch_row();
		
		
		return $tempRow;
		//echo 'hello';
		
	}
	
	
	
	
	public function getFeaturedItems()
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `item_tbl`
				  WHERE ISACTIVE = 1 AND
				  ISFEATURED = 1";
		$this->db->setQuery(htmlentities($sql), 'getFeaturedItem');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureItem[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureItem;
	}
	
	public function getAllItems()
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `item_tbl`
				  WHERE ISACTIVE = 1";
		$this->db->setQuery(htmlentities($sql), 'getAllItems');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureItem[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureItem;
	}
	
	public function getFeaturedSellers()
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `members_tbl`
				  WHERE ISACTIVE = 1 AND
				  ISFEATURED = 1";
		$this->db->setQuery($sql, 'getFeaturedSellers');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureSeller[] = $this->getStoreInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureSeller;
	}
	
	public function getNewItems()
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `item_tbl`
				  WHERE ISACTIVE = 1
				  ORDER BY ADDEDON DESC LIMIT 8";
		$this->db->setQuery(htmlentities($sql), 'getNewItems');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arr[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arr;
	}
	
	
	public function getItemByGlobalCategory($pGlobalCatID)
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `item_tbl`
				  WHERE ISACTIVE = 1 AND
				  GLOBALCATID = $pGlobalCatID";
		$this->db->setQuery(htmlentities($sql), 'getItemByGlobalCategory');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureItem[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureItem;
	}
	
	
	
	public function getItemBySubGlobalCategory($pSubGlobalCatID)
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `item_tbl`
				  WHERE ISACTIVE = 1 AND
				  SUBGLOBALCATID = $pSubGlobalCatID";
		$this->db->setQuery(htmlentities($sql), 'getItemBySubGlobalCategory');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureItem[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureItem;
	}
	
	
	
	
	public function getStoreItem($pPage, $pStoreID, $filter, $show = '')
	{
		if($show == ''):
			$start = (($pPage - 1) * ITEM_PAGE_LIMIT);
			$range = ITEM_PAGE_LIMIT;
			$limit = " LIMIT $start, $range";
		else:
			$limit = '';
		endif;
		
		switch($filter)
		{
			case 'hide':
				$criteria = "ISACTIVE = 1 AND ISHIDDEN = 1 AND STOREID = $pStoreID";
			break;
			
			case 'expire':
				$criteria = "ISACTIVE = 1 AND STOREID = $pStoreID AND ID IN (SELECT ID FROM expireditems_v)";
			break;
			
			default:
				$criteria = "ISACTIVE = 1 AND STOREID = $pStoreID AND ISHIDDEN = 0 AND ID NOT IN (SELECT ID FROM expireditems_v)";
			break;
		}
		$this->totalRecords = $this->getTotalRecords('item_tbl','ID', $criteria);
			
		
		$sql = 	"SELECT ID,NAME,PRICE, ADDEDON FROM item_tbl
 				 WHERE $criteria
  				 $limit";
				
		$this->db->setQuery(htmlentities($sql), 'getStoreItem');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	
	public function getStoreItemForDisplay($pPage, $pCatID, $pStoreID = null, $show = '', $filter = '')
	{
		if($show == ''):
			$start = (($pPage - 1) * ITEM_PAGE_LIMIT);
			$range = ITEM_PAGE_LIMIT;
			$limit = " LIMIT $start, $range";
		else:
			$limit = '';
		endif;
		
		if($pCatID == 0)
			$criteria = "ISACTIVE = 1 AND 
						STOREID = $pStoreID AND 
						ISHIDDEN = 0 AND 
						ID NOT IN (SELECT ID FROM expireditems_v)";	
		else
			$criteria = "ISACTIVE = 1 AND 
						STOREID = $pStoreID AND 
						ISHIDDEN = 0 AND 
						ID NOT IN (SELECT ID FROM expireditems_v) AND 
						CATEGORYID = $pCatID";	
						
		//filter switch
		switch($filter)
		{
			case 'latest':
				$criteria .= " ORDER BY ADDEDON DESC";
			break;
			
			case 'lowtohigh':
				$criteria .= " ORDER BY PRICE ASC";
			break;
			
			case 'hightolow':
				$criteria .= " ORDER BY PRICE DESC";
			break;
				
		}
		//Saleable items
		
		
		$this->totalRecords = $this->getTotalRecords('item_tbl','ID', $criteria);
		
		$sql = "SELECT * FROM `v_storeitems`
					  WHERE $criteria
					  $limit";
		$this->db->setQuery(htmlentities($sql), 'getStoreItemForDisplay');
		
		if($this->showQuery) 
			$this->printQuery();
			
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
	
		return $tempArray;

		/*$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		

		$this->db->setQuery(htmlentities($sql), 'getStoreItemForDisplay');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureItem[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureItem;*/
	}
	
	public function getAllItems_xAdmin($pPage, $pFeatured = null)
	{
		//$sql = 	$this->QM_select("members_tbl","*", 1,1);
		if($pFeatured):
			$this->totalRecords = $this->getSingleData('item_tbl','COUNT(*)', "ISACTIVE = 1 AND ISFEATURED = $pFeatured");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM item_tbl WHERE ISACTIVE = 1 AND ISFEATURED = $pFeatured
					ORDER BY NAME ASC
					LIMIT $start, $limit";
		else:
			$this->totalRecords = $this->getSingleData('item_tbl','COUNT(*)', "ISACTIVE = 1");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM item_tbl 
					WHERE ISACTIVE = 1
					ORDER BY NAME ASC
					LIMIT $start, $limit";
		endif;
					
				
		$this->db->setQuery(htmlentities($sql), 'getAllItems_xAdmin');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
	
		return $tempArray;
		
	}
	
	
	
	
	public function getFirstItemImage($pItemID)
	{
		$sql = "SELECT IMAGENAME FROM `itemimages_tbl`
				  WHERE `ITEMID` = $pItemID";
		/*echo 'store::getFirstItemImage:: '.$sql;*/
		$this->db->setQuery(htmlentities($sql), 'getFirstItemImage');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
		
		$rowImage = $this->db->fetch_row();
		$img = $rowImage[IMAGENAME];
		
		return $img;

	}
	
	public function getLastID()
	{
		return $this->db->getLastInsertedID();
	}
	
	public function getStoreName($pID)
	{
		$storeName = $this->getSingleData('members_tbl', 'STORENAME', 'ID='.$pID);
		return $storeName;
	}
	
	public function getShopName($pID)
	{
		$storeName = $this->getSingleData('members_tbl', 'SHOPNAME', 'ID='.$pID);
		return $storeName;
	}
	
	public function getStoreID($pName)
	{
		$storeID = $this->getSingleData('members_tbl', 'ID', 'STORENAME = '.CN_S($pName));
		return $storeID;
	}
	
	public function getItemName($pID)
	{
		$itemName = $this->getSingleData('item_tbl', 'NAME', 'ID='.$pID);
		return $itemName;
	}
	
	public function getMemberName($pID)
	{
		$memName = $this->getSingleData('members_tbl', 'CONCAT(FIRSTNAME,\' \',LASTNAME)', 'ID='.$pID);
		return $memName;
	}
	
	public function getMemberID($pMemberName)
	{
		
		$memberID = $this->getSingleData('members_tbl', 'ID', 'STORENAME = '.CN_S($pMemberName));
		return $memberID;
	}


	public function getPageModules($pPageID)
	{

		$sql = "SELECT M.*, P.NAME, P.SIDEBAR
				FROM (
				pagesides_tbl M
				JOIN mallpages_tbl P ON (
				M.PAGEID = P.ID))
				WHERE M.PAGEID = $pPageID
				ORDER BY M.PRIORITY ASC";

		$this->db->setQuery($sql, 'getPageModules');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
		
	}
	
	
	public function getStoreCategory($pStoreID =  null)
	{
		if($pStoreID == null)
			$pStoreID = $_COOKIE[memberid];

			
		$sql = "SELECT ID, NAME, PRIORITY FROM category_tbl
				WHERE STOREID = $_COOKIE[memberid]
				ORDER BY PRIORITY ASC";

		$this->db->setQuery(htmlentities($sql), 'getStoreCategory');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
		
	}
	
	public function getHelpArea()
	{
			
		$sql = 	$this->QM_select("help_tbl","*", 1,1);

		$this->db->setQuery(htmlentities($sql), 'getHelpArea');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
		
	}
	
	public function getFaqs($pPage, $pSortOrder='ASC')
	{
		$this->totalRecords = $this->getSingleData('mallfaqs_tbl','COUNT(*)');
			$start = (($pPage - 1) * ADMINPAGELIMIT);
			$limit = ADMINPAGELIMIT;
			
			if($pSortOrder == 'PRIORITY'):
				$sql = "SELECT * FROM `mallfaqs_tbl`
						  ORDER BY PRIORITY ASC
						  LIMIT $start, $limit";	
			else:			
				$sql = "SELECT * FROM `mallfaqs_tbl`
						  ORDER BY QUESTION $pSortOrder
						  LIMIT $start, $limit";
			endif;
			
		$this->db->setQuery(htmlentities($sql), 'getFaqs');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
		
	}
	
	public function getHelp($pArea)
	{
			
		$sql = 	$this->QM_select("help_tbl","*", 'ID',"$pArea");

		$this->db->setQuery(htmlentities($sql), 'getHelpArea');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
		
	}
	
	public function getFaq($pID)
	{
			
		$sql = 	$this->QM_select("mallfaqs_tbl","*", 'ID',"$pID");

		$this->db->setQuery(htmlentities($sql), 'getFaq');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		return $tempArray;
		
	}
	
	
	public function getBuyerOrders($pStoreID =  null)
	{
		if($pStoreID == null)
			$memID = $_COOKIE[memberid];

		$sql = "SELECT O.ORDERNUMBER, O.ORDERDATE, O.ORDERSTATUS, O.STOREID, M.FIRSTNAME, M.LASTNAME, M.COUNTRYNAME, M.CITY, M.ADDRESS, M.ADDRESS2, M.ZIPCODE, M.STATENAME, M.PROVINCE, M.PHONENUMBER, M.STORENAME
				  FROM (
				  orders_tbl O
				  JOIN members_tbl M ON (
				  O.BUYERID = M.ID))
				  WHERE O.BUYERID = $memID";

		$this->db->setQuery(htmlentities($sql), 'getStoreCategory');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getOrdersDetail($pOrderNumber)
	{
		if($pStoreID == null)
			$memID = $_COOKIE[memberid];

		$sql = "SELECT O.ITEMID, O.QUANTITY, O.ITEMATTRIBUTES, I.NAME, I.PIC1, I.PRICE
				  FROM (
				  orderdetail_tbl O
				  JOIN item_tbl I ON (
				  O.ITEMID = I.ID))
				  WHERE O.ORDERNUMBER = '$pOrderNumber'";

		$this->db->setQuery(htmlentities($sql), 'getBuyerOrdersDetail');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getPlacedOrders()
	{

		$sql = "SELECT ORDERNUMBER, STOREID, STORENAME, (ORDERAMOUNT + SHIPPINGAMOUNT) AS TOTALAMOUNT
				FROM v_orders
				WHERE ORDERSTATUS = 'PLACED'
				AND BUYERID = $_COOKIE[memberid]
				AND ISPAID = 0";

		$this->db->setQuery(htmlentities($sql), 'getPlacedOrders');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getSellerOrders($pStoreID =  null)
	{
		if($pStoreID == null)
			$memID = $_COOKIE[memberid];

		$sql = "SELECT O.ORDERNUMBER, O.ORDERDATE, O.ORDERSTATUS, O.AMOUNTPAID, M.ID, M.FIRSTNAME, M.LASTNAME
				  FROM (
				  orders_tbl O
				  JOIN members_tbl M ON (
				  O.BUYERID = M.ID))
				  WHERE O.STOREID = $memID";

		$this->db->setQuery(htmlentities($sql), 'getSellerOrders');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getSubCategory($pCategoryID = 63)
	{
		$sql = 	$this->QM_select("subcategory_tbl","ID;NAME", 
								"CATEGORYID","'$pCategoryID'");

		$this->db->setQuery(htmlentities($sql), 'getSubCategory');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getGlobalSubCategory($pGlobalCatID)
	{
		$sql = "SELECT * FROM subglobalcategory_tbl 
				WHERE GLOBALCATID = $pGlobalCatID
				ORDER BY PRIORITY";

		$this->db->setQuery(htmlentities($sql), 'getGlobalSubCategory');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getItemShipping($pItemID)
	{
		$sql = 	$this->QM_select("shipping_tbl","*", 
								"ITEMID","'$pItemID'");

		$this->db->setQuery(htmlentities($sql), 'getItemShipping');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getStoreItems()
	{
		$sql = 	$this->QM_select("item_tbl","ID;NAME;PIC1;PRICE;DETAIL", 
								"STOREID",$_COOKIE[memberid]);

		$this->db->setQuery(htmlentities($sql), 'getStoreItems');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getSellers($pPage, $pSellerName)
	{
			$this->totalRecords = $this->getTotalRecords('members_tbl','ID',"STORENAME LIKE '%$pSellerName%'");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
					
			$sql = 	"SELECT M.ID,M.STORENAME,M.SELLERPICTURE,M.REGISTEREDON, COUNT(I.NAME) AS TOTALITEMS 
					FROM (members_tbl M
					JOIN item_tbl I ON (
				    M.ID = I.STOREID))
					WHERE M.STORENAME LIKE '%$pSellerName%'
					GROUP BY M.STORENAME
					ORDER BY M.STORENAME ASC
					LIMIT $start, $limit";

		$this->db->setQuery(htmlentities($sql), 'getSellers');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		return $tempArray;
		
	}
	
		
		
	public function getItemByGlobalCategory_search($pPage, $pItemName, $pGlobalCatID)
	{
		if($pGlobalCatID == ''):
		
			$this->totalRecords = $this->getTotalRecords('item_tbl','ID',"NAME LIKE '%$pItemName%'");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
					
			$sql = 	"SELECT * FROM item_tbl I
					WHERE I.NAME LIKE '%$pItemName%'
					ORDER BY I.NAME ASC
					LIMIT $start, $limit";
		else:

			$this->totalRecords = $this->getTotalRecords('item_tbl','ID',"NAME LIKE '%$pItemName%' AND GLOBALCATID = $pGlobalCatID");
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
					
			$sql = 	"SELECT * FROM item_tbl I
					WHERE I.NAME LIKE '%$pItemName%'
					AND GLOBALCATID = $pGlobalCatID
					ORDER BY I.NAME ASC
					LIMIT $start, $limit";
		endif;

		$this->db->setQuery(htmlentities($sql), 'getItemByGlobalCategory_search');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getItemByAdvanceSearch($pPage, $pCriteria)
	{
		$this->totalRecords = $this->getTotalRecords('item_tbl','ID',$pCriteria);
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
					
			$sql = 	"SELECT * FROM item_tbl WHERE ".$pCriteria." 			
					ORDER BY NAME ASC
					LIMIT $start, $limit";
		
		$this->db->setQuery(html_entity_decode($sql), 'getItemByAdvanceSearch');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	

	/*public function getNewItems()
	{
	
		$arrAlreadySelected = array();
		// POPULATING AN ARRAY WITH IDs
		$sql = "SELECT ID FROM `item_tbl`
				  WHERE ISACTIVE = 1 AND
				  ISFEATURED = 1";
		$this->db->setQuery(htmlentities($sql), 'getFeaturedItem');
		 
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery();
				
		$arrIDs = array();
		while ($row = $this->db->fetch_array()) {
        	$arrIDs[] = $row;
		}
		
				
		if(count($arrIDs) == 0)
		{
			return null;
		}
		
		for($i=0; $i<$this->featuredItemLimit; $i++)
		{
		
			$randID = rand(0,(count($arrIDs)-1));
			
			if(!in_array($randID,$arrAlreadySelected))
			{
				$arrFeatureItem[] = $this->getItemInfo($arrIDs[$randID][ID]);
				$arrAlreadySelected[$i] =  $randID;
			}
		}
		//print_r($arrFeatureStore);		
		return $arrFeatureItem;
	}*/
	
	public function getItemInfo($pItemID)
	{
		$sql = "SELECT * FROM `v_storeitems`
				  WHERE `ID` = $pItemID";
		//echo $sql;
		$this->db->setQuery($sql, 'getItemInfo');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		return $this->db->fetch_row();

	}
	
	
	public function getStoreInfo($pStoreID = null)
	{
	
		if($pStoreID == null)
			$pStoreID = $_COOKIE[memberid];
			
		$sql = "SELECT * FROM `members_tbl`
				  WHERE `ID` = $pStoreID";
		//echo $sql;
		$this->db->setQuery(htmlentities($sql), 'getStoreInfo');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		return $this->db->fetch_row();

	}
	
	public function getGlobalCategory()
	{
		$sql = "SELECT * FROM `globalcategory_tbl`
				  ORDER BY PRIORITY ASC";
		$this->db->setQuery(htmlentities($sql), 'getGlobalCategory');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getGlobalCategory_admin($pPage, $pSortOrder='ASC')
	{
		$this->totalRecords = $this->getSingleData('globalcategory_tbl','COUNT(*)');
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM `globalcategory_tbl`
					  ORDER BY NAME $pSortOrder
					  LIMIT $start, $limit";
		$this->db->setQuery(htmlentities($sql), 'getGlobalCategory');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getCountry()
	{
		$sql = "SELECT * FROM `country_tbl`
				  ORDER BY name ASC";
		$this->db->setQuery(htmlentities($sql), 'getCountry');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getRentHistory($pStoreID)
	{
		$sql = "SELECT * FROM `rentreceived_tbl`
				WHERE STOREID = $pStoreID
				ORDER BY PAIDON DESC";
				
	  $this->db->setQuery(htmlentities($sql), 'getRentHistory');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getStates()
	{
		$sql = "SELECT * FROM `states_tbl`
				  ORDER BY name ASC";
		$this->db->setQuery(htmlentities($sql), 'getStates');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getInbox($pFilter)
	{
		switch($pFilter)
		{
			case 'all':
			$sql = 	"SELECT I . * , M.STORENAME, M.SELLERPICTURE
				FROM (
				mails_tbl I
				JOIN members_tbl M ON (I.SENTBY = M.ID )
				) WHERE 
				I.SENTTO = ".$_COOKIE[memberid]." AND
				I.ISDELETED_R != '1'
				ORDER BY I.SENTDATE DESC";		//$this->QM_select("vedios_tbl","*", ,1);
			break;
			
			case 'unread':
			$sql = 	"SELECT I . * , M.STORENAME
				FROM (
				mails_tbl I
				JOIN members_tbl M ON (I.SENTBY = M.ID )
				) WHERE 
				I.SENTTO = ".$_COOKIE[memberid]." AND
				I.ISDELETED_R != '1' AND
				I.ISREAD_R != 1
				ORDER BY I.SENTDATE DESC";		//$this->QM_select("vedios_tbl","*", ,1);
			break;
			
			case 'read':
			$sql = 	"SELECT I . * , M.STORENAME
				FROM (
				mails_tbl I
				JOIN members_tbl M ON (I.SENTBY = M.ID )
				) WHERE 
				I.SENTTO = ".$_COOKIE[memberid]." AND
				I.ISDELETED_R != '1' AND
				I.ISREAD_R = 1
				ORDER BY I.SENTDATE DESC";		//$this->QM_select("vedios_tbl","*", ,1);
			break;
			
		}
				
		$this->db->setQuery(htmlentities($sql), 'getInbox');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		//echo 'hello';
		
	}
	public function getFreindsName($pUserName)
	{
		$sql = 	"SELECT STORENAME FROM members_tbl
				WHERE ISACTIVE = 1
				AND STORENAME LIKE '".$pUserName."%'";
				
				
				
		$this->db->setQuery(htmlentities($sql), 'getFreindsName');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	public function getConversations($pPage, $memID)
	{
		$this->totalRecords = $this->getTotalRecords('mails_tbl','ID', "(SENTBY = $memID OR SENTTO = $memID) AND TAILID = 0");
			$start = (($pPage - 1) * CONVO_PAGE_LIMIT);
		
			$limit = CONVO_PAGE_LIMIT;
		
		$sql = 	"SELECT ID, SENTTO AS MEMBERID, SUBJECT, MESSAGE, SENTDATE FROM mails_tbl
				WHERE (SENTBY = $memID OR SENTTO = $memID) AND TAILID = 0
				ORDER BY SENTDATE DESC
				LIMIT $start, $limit";
				
		$this->db->setQuery(htmlentities($sql), 'getConversations');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	public function getLooks($pPage, $memID, $show = '')
	{
		if($show == ''):
			$start = (($pPage - 1) * ITEM_PAGE_LIMIT);
			$range = ITEM_PAGE_LIMIT;
			$limit = " LIMIT $start, $range";
		else:
			$limit = '';
		endif;
		
		
		$this->totalRecords = $this->getTotalRecords('looks_tbl','ID', "STOREID = $memID AND ISPUBLISHED = 1");
				
		
		$sql = 	"SELECT * FROM `looks_tbl`
				 WHERE STOREID = $memID AND ISPUBLISHED = 1
				ORDER BY CREATEDON DESC
				$limit";
				
		$this->db->setQuery(htmlentities($sql), 'getLooks');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	public function markConvo($convoID, $status)
	{
		$sql = 	"UPDATE mails_tbl SET ISREAD_R = $status WHERE ID = $convoID OR TAILID = $convoID";
				
		$this->db->setQuery(htmlentities($sql), 'markConvo');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
	}
	
	public function isReadConvo($convoID)
	{
		$res = $this->getArrayData('mails_tbl', 'ID', "(ID = $convoID OR TAILID = $convoID) AND ISREAD_R = 0");
		
		if($res):
			return true;			//Yes there is un - read messages
		else:
			return false;			//No there is not any un - read messages
		endif;
	}
	
	public function getConversations_detail($conID)
	{
		$sql = 	"SELECT I . * , M.STORENAME, M.SELLERPICTURE
				FROM (
				mails_tbl I
				JOIN members_tbl M ON (I.SENTBY = M.ID ))
				WHERE I.ID = $conID OR I.TAILID = $conID
				ORDER BY I.SENTDATE DESC";
								
				
		$this->db->setQuery(htmlentities($sql), 'getConversations_detail');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	public function getOrdersFeedbacks($pPage, $memID, $filter)
	{
		if($filter == 'b')
		{
			$criteria = "(FBBY= $memID OR FBTO = $memID) AND FBFROM = 'BUYER'";
		}elseif($filter == 's')
		{
			$criteria = "(FBBY= $memID OR FBTO = $memID) AND FBFROM = 'SELLER'";
		}else
		{
			$criteria = "FBBY= $memID OR FBTO = $memID";
		}
		
		$this->totalRecords = $this->getTotalRecords('orderfeedbacks_tbl','ID', $criteria);
			$start = (($pPage - 1) * FEEDBACK_PAGE_LIMIT);
		
			$limit = FEEDBACK_PAGE_LIMIT;
		
		$sql = 	"SELECT * FROM orderfeedbacks_tbl
				WHERE $criteria
				ORDER BY FBON DESC
				LIMIT $start, $limit";
				
		$this->db->setQuery(htmlentities($sql), 'getOrdersFeedbacks');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	public function getAwaitedFeedbacks($pPage, $memID)
	{
		
		$criteria = "BUYERID= $memID AND ISFEEDBACK = 0";
		
		$this->totalRecords = $this->getTotalRecords('orders_tbl','ORDERNUMBER', $criteria);
			$start = (($pPage - 1) * FEEDBACK_PAGE_LIMIT);
		
			$limit = FEEDBACK_PAGE_LIMIT;
		
		$sql = 	"SELECT * FROM orders_tbl
				WHERE $criteria
				ORDER BY ORDERDATE DESC
				LIMIT $start, $limit";
				
		$this->db->setQuery(htmlentities($sql), 'getAwaitedFeedbacks');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	
	//THIS FUNCTION IS GETTING PURCHASES DETAIL (FROM ORDERS TABLE) FOR BUYER AREA
	public function getPurchases($pPage, $memID, $filter)
	{
				
		if($filter != 'a')
		{
			$criteria = "BUYERID = $memID AND ORDERDATE LIKE '$filter'";
		}else
		{
			$criteria = "BUYERID = $memID";
		}


		$this->totalRecords = $this->getTotalRecords('orders_tbl','ORDERNUMBER', $criteria);
			$start = (($pPage - 1) * PURCHASE_PAGE_LIMIT);
		
			$limit = PURCHASE_PAGE_LIMIT;
		
		$sql = 	"SELECT * FROM orders_tbl
				WHERE $criteria
				ORDER BY ORDERDATE DESC
				LIMIT $start, $limit";
				
		$this->db->setQuery(htmlentities($sql), 'getPurchases');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	
	//THIS FUNCTION IS GETTING ORDERS FOR SELLERS AREA
	public function getOrders($pPage, $memID, $filter)
	{
				
		if($filter != 'a')
		{
			$criteria = "STOREID = $memID AND ORDERDATE LIKE '$filter'";
		}else
		{
			$criteria = "STOREID = $memID";
		}


		$this->totalRecords = $this->getTotalRecords('orders_tbl','ORDERNUMBER', $criteria);
			$start = (($pPage - 1) * ORDER_PAGE_LIMIT);
		
			$limit = ORDER_PAGE_LIMIT;
		
		$sql = 	"SELECT * FROM orders_tbl
				WHERE $criteria
				ORDER BY ORDERDATE DESC
				LIMIT $start, $limit";
				
		$this->db->setQuery(htmlentities($sql), 'getOrders');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
	
		return $tempArray;
		
	}
	
	
	public function showHelp($pHelpArea, $id)
	{
		$help = $this->getSingleData('help_tbl', 'HELP', "AREA = '$pHelpArea'"); 
		
		$html = '<a id="'.$id.'" href="#" title="'.$help.'">
				<img src="'.fullURL("iconset/help_16.png").'" /></a>
				<script type="text/javascript">
				$("#'.$id.'").tipsy({gravity: "w"});
				</script>';
				
		if($help == null)
			return '';
		else
			return $html;
	}
		
		
	public function hideItem($pIDs)
	{
		$sql = "UPDATE item_tbl SET ISHIDDEN = 1
				WHERE ID IN ($pIDs)";
				
		$this -> Run($sql, 'hideItem');
	}
	
	public function unhideItem($pIDs)
	{
		$sql = "UPDATE item_tbl SET ISHIDDEN = 0
				WHERE ID IN ($pIDs)";
				
		$this -> Run($sql, 'hideItem');
	}
	
	public function delItems($pIDs)
	{
		$sql = "DELETE FROM item_tbl 
				WHERE ID IN ($pIDs)";
				
		$this -> Run($sql, 'delItems');
		
		$sql  = "DELETE FROM itemimages_tbl 
   				 WHERE ITEMID IN ($pIDs)";
				 
		$this -> Run($sql, 'delItems');
				 
	}
	
	
	public function delLookItems($pIDs)
	{
		$sql = "DELETE FROM lookitems_tbl 
				WHERE ITEMID IN ($pIDs)";
				
		$this -> Run($sql, 'delLookItems');
					 
	}
	


	
public function sendMessage($pDA, $tailID = 0)	//$Data Array
{
	//Setting Level is read
	$to = $this->getMemberID($pDA[to]);
	if(empty($to))
		return false;
	
	$value = $_COOKIE[memberid].'|'.$to.'|'.CN_S($pDA[subject]).'|'.CN_S($pDA[message]).'|NOW()|0|0|0|0|'.$tailID;
	$sql = $this->QM_insert_textarea("mails_tbl","SENTBY|SENTTO|SUBJECT|MESSAGE|SENTDATE|ISREAD_S|ISREAD_R|ISDELETED_S|ISDELETED_R|TAILID", $value);
	$this->db->setQuery(htmlentities($sql), 'sendMessage');
	/*echo $sql;
	exit;*/
		
	if($this->showQuery) 
		$this->printQuery();

	if($this->db->executeQuery())
	{
		$_SESSION[mailid] = $this->getLastID();
		return true;
	}
	else
	{
		return false;
	}

}
	public function getShippingRate($pItemID)
	{
		$sql = "SELECT * FROM `shipping_tbl` WHERE `ITEMID` = $pItemID
				  ORDER BY `COUNTRY` ASC";
		$this->db->setQuery(htmlentities($sql), 'getShippingRate');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	public function getItemAttributes($pItemID)
	{
		$sql = "SELECT * FROM `itemattributes_tbl` WHERE `ITEMID` = $pItemID
				  ORDER BY `NAME` ASC";
		$this->db->setQuery(htmlentities($sql), 'getItemAttributes');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	
	public function getAllStores_Cart()
	{
		/*$sql = "SELECT DISTINCT (C.STOREID)
				  FROM cart_tbl C
				  WHERE C.SESSIONID = '".session_id()."'";*/
				  
		$sql = "SELECT DISTINCT (C.STOREID)
				  FROM cart_tbl C
				  WHERE C.BUYERID = $_COOKIE[memberid]";
			  
		$this->db->setQuery($sql, 'getAllStores_Cart');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getStoreCart($pStoreID,$pSessionID)
	{
		/*$sql = "SELECT I.NAME, I.QUANTITY AS STOCK, I.PRICE, I.STOREID, I.PIC1, C.QUANTITY, C.ITEMID, C.ID, C.ITEMATTRIBUTES, C.BUYERID
				  FROM (
				  cart_tbl C
				  JOIN item_tbl I ON (
				  C.ITEMID = I.ID))
				  WHERE C.SESSIONID = '$pSessionID'
  	   		  AND C.STOREID =$pStoreID";*/
		$sql = "SELECT * FROM v_cartitems
				WHERE STOREID = $pStoreID
				AND BUYERID = $_COOKIE[memberid]";
				  
		$this->db->setQuery(htmlentities($sql), 'getStoreCart');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getRentReceived($pPage,$pStatus = null)
	{
		$criteria = ($pStatus == 'All') ? '1 = 1' : "RENTSTATUS = '$pStatus'";
		
		$this->totalRecords = $this->getSingleData('members_tbl','COUNT(*)', $criteria);
			$start = (($pPage - 1) * ADMINPAGELIMIT);
		
			$limit = ADMINPAGELIMIT;
			$sql = "SELECT * FROM `members_tbl`
					WHERE $criteria
					LIMIT $start, $limit";
		$this->db->setQuery(htmlentities($sql), 'getGlobalCategory');
		
		
						  
		$this->db->setQuery(htmlentities($sql), 'getRentReceived');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	
	function getItemShipping_Cart($pItemID)
	{
		$country = $this->getSingleData('members_tbl', 'COUNTRYNAME', 'ID='.$_COOKIE[memberid]);
		
		$arr_item_country = $this->getRowData('shipping_tbl', "FIRST,SECOND", "COUNTRY = '".$country."' AND ITEMID = ".$pItemID."");
		$arr_item_else = $this->getRowData('shipping_tbl', "FIRST,SECOND", "COUNTRY = 'ELSE WHERE' AND ITEMID = ".$pItemID."");
		
		
		
		if(!$arr_item_country)
		{
			return $arr_item_else;
		}
		else
		{		
			//print_r($arr_item_else);
			return $arr_item_country;
		}
		
		
	
	}
	
	public function loadCart()
	{
		$sql = "SELECT I.NAME, I.PRICE, I.PIC1, C.* FROM (
				cart_tbl C
				JOIN item_tbl I ON ( C.ITEMID = I.ID )
				) 
				WHERE C.`SESSIONID` = '".session_id()."'";
		$this->db->setQuery(htmlentities($sql), 'loadCart');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function loadFavorite()
	{
		$sql = "SELECT I.NAME, I.PRICE, I.PIC1, I.STOREID, F.* FROM (
				favorites_tbl F
				JOIN item_tbl I ON ( F.ITEMID = I.ID )
				) 
				WHERE F.`MEMBERID` = ".$_COOKIE[memberid]."";
		$this->db->setQuery(htmlentities($sql), 'loadFavorite');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
		
	}
	
	public function getItemFromCart()
	{
		$sql = "SELECT COUNT(ID) AS ITEMINCART FROM cart_tbl
				WHERE `SESSIONID` = '".session_id()."'";
		$this->db->setQuery(htmlentities($sql), 'loadCart');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$row = $this->db->fetch_row();
		
		//print_r($tempArray);
		
		return $row[ITEMINCART];
		
	}
	
	
	public function getFavoriteItems()
	{
		$sql = "SELECT COUNT(ID) AS FAVITEMS FROM favorites_tbl
				WHERE `MEMBERID` = ".$_COOKIE[memberid];
		$this->db->setQuery(htmlentities($sql), 'getFavoriteItems');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$row = $this->db->fetch_row();
		
		//print_r($tempArray);
		
		return $row[FAVITEMS];
		
	}
	
	
	
	
	public function getItemRating($pItemID)
	{
		$sql = "SELECT 
			(SUM( RATING ) / (
			(SELECT COUNT( * ) FROM `itemrating_tbl` WHERE ITEMID = $pItemID )
			*100) *100) AS RATING
			FROM `itemrating_tbl`
			WHERE ITEMID = $pItemID";
			
		$this->db->setQuery(htmlentities($sql), 'getItemRating');
		 
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
				
		$tempRow = $this->db->fetch_row();
		
		return $tempRow[RATING];
		
	}
	
	public function analyzeFeedback($pStoreID)
{

	$sql = "SELECT ID
			  FROM `feedbacks_tbl` 
			  WHERE `STOREID` = '$pStoreID'";
				 
		//echo 'store::setAllStoresArray:: '.$sql;
		//exit;
	$this->db->setQuery(htmlentities($sql), 'analyzeFeedback');
	
	$this->db->executeQuery();
	
	$totalFeedback = $this->db->total_records();
	
		
	$sql = "SELECT ID
			  FROM `feedbacks_tbl` 
			  WHERE `STOREID` = '$pStoreID'
			  AND COMMENTLEVEL = 'P'";
				 
		//echo 'store::setAllStoresArray:: '.$sql;
		//exit;
		
	$this->db->setQuery(htmlentities($sql), 'analyzeFeedback');

	$this->db->executeQuery();
	
	$positiveFeedback = $this->db->total_records();
	
	$ratio = ($totalFeedback == 0) ? 0 : ($positiveFeedback/$totalFeedback) * 100;
	
	$feedback = $totalFeedback.', '.round($ratio,2).'% positive';
	
	return $feedback;

}
	
	public function isMember($pUserName,$pPassword, &$pUserID)
	{
		$pPassword = md5($pPassword);
		
		$sql = 	$this->QM_select("members_tbl","ID", 
								"STORENAME;PASSWORD","'$pUserName';'$pPassword'");

		$this->db->setQuery(htmlentities($sql), 'isMember');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$data = $this->db->fetch_array(1);
		/*print_r($data);
		exit;*/
		
		if($data)
		{
			$pUserID = $data[ID];
			return true;
		}
		else
		{
			return false;
		}
		
	}


public function isAdmin($pEmail,$pPassword)
	{
		$pPassword = md5($pPassword);
		
		$sql = 	$this->QM_select("admin_tbl","ID", 
								"EMAIL;PASSWORD","'$pEmail';'$pPassword'");

		$this->db->setQuery($sql, 'isAdmin');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$data = $this->db->fetch_array(1);
		/*print_r($data);
		exit;*/
		
		if($data)
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}

	
	public function isAlreadyExist($pValue, $pField)
	{
	
		$sql = 	$this->QM_select("members_tbl","ID", 
								"$pField","'$pValue'");

		$this->db->setQuery($sql, 'isAlreadyExist');
		
		if($this->showQuery) 
			$this->printQuery();
				
		$this->db->executeQuery();
		
		$data = $this->db->fetch_array(1);
		/*print_r($data);
		exit;*/
		
		if($data)
		{
			return true;
		}
		else
		{
			return false;
		}
		
	}

	
		
//GETS========================================================================================================================GETS




//SETS========================================================================================================================SETS

public function addToCart($itemid, $storeid)
{
	$fields =	'ITEMID;QUANTITY;SESSIONID;STOREID;BUYERID';
				 
	$buyerID = $_COOKIE[memberid];
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($itemid).';
				 '.CN_I(1).';
				 '.CN_S(session_id()).';
				 '.CN_I($storeid).';
 				 '.CN_I($buyerID).'';
				 
				 
	$sql = $this->QM_insert("cart_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'addToCart');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}


public function addToFavorite($pDA)
{
	$memID = $_COOKIE[memberid];
	$dt = date('Y-m-d');
	
	//Deleting is already exist
	$values =	''.CN_I($pDA[itemid]).';
				 '.CN_I($memID).'';
				 
	$sql = $this->QM_delete("favorites_tbl", 'ITEMID;MEMBERID', $values);
	$this->db->setQuery(htmlentities($sql), 'addToFavorite');
	$this->db->executeQuery();
	
	
	$fields =	'ITEMID;MEMBERID;ADDEDON';
				 
	
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($pDA[itemid]).';
				 '.CN_I($memID).';
 				 '.CN_S($dt).'';
				 
				 
	$sql = $this->QM_insert("favorites_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'addToFavorite');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}



public function itemViewed($pItemID)
{
	
	$itemViewed = $this->getSingleData('item_tbl', 'ITEMVIEWED', 'ID='.$pItemID);	
	
	$itemViewed +=1;
	
	$sql = $this->QM_update("item_tbl", 'ITEMVIEWED', $itemViewed, 'ID', $pItemID);

	$this->db->setQuery(htmlentities($sql), 'itemViewed');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		unset($_SESSION[lastcatid]);
		$_SESSION[lastcatid] = $this->db->getLastInsertedID();
		return true;
	else:
		return false;
	endif;
}

public function setShipping($pDA)
{
	$fields =	'ITEMID;COUNTRY;FIRST;SECOND';
				 
	$itemid = $_COOKIE[lastid];
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($itemid).';
				 '.CN_S($pDA[country]).';
				 '.CN_N($pDA[rate1]).';
				 '.CN_N($pDA[rate2]).'';
				 
				 
	$sql = $this->QM_insert("shipping_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'setShipping');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}


public function setAttributes($pDA)
{
				 
	$itemid = $_COOKIE[lastid];
	$storeid = $_COOKIE[memberid];


	$sql = "INSERT INTO itemattributes_tbl (ITEMID,STOREID,NAME,ATTRIBUTEVALUE)
									VALUES ($itemid, $storeid, ".CN_S($pDA[attributename]).", ".CN_S($pDA[attributes]).")";
	
	$this->db->setQuery(htmlentities($sql), 'setAttribtues');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}

public function updateAttributes($pDA)
{
				 
	$itemid = $pDA[itemid];
	$storeid = $_COOKIE[memberid];


	$sql = "INSERT INTO itemattributes_tbl (ITEMID,STOREID,NAME,ATTRIBUTEVALUE)
									VALUES ($itemid, $storeid, ".CN_S($pDA[attributename]).", ".CN_S($pDA[attributes]).")";
	
	$this->db->setQuery(htmlentities($sql), 'setAttribtues');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}

public function isExist($pTable,$f, $v)
{
	$data = $this->getSingleData($pTable, $f, $f.' = '.CN_S($v));
	if($data):
		
		$_SESSION[v] .= "$f is already Exists";
		
	endif;
}

public function updateShipping($pDA)
{
	$fields =	'ITEMID;COUNTRY;FIRST;SECOND';
				 
	$values =	''.CN_I($pDA[itemid]).';
				 '.CN_S($pDA[country]).';
				 '.CN_N($pDA[rate1]).';
				 '.CN_N($pDA[rate2]).'';
				 
				 
	$sql = $this->QM_insert("shipping_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'setShipping');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}


public function orderIsConfirmed($pStoreID, $buyerID, $pAmountWithoutShipping, $pOrderNumber)
{

		
	//Now puttign the cart items into order dedtail table [orderdetail_tbl]
	$sql = "INSERT INTO `orderdetail_tbl`
								(`ITEMID`, `QUANTITY`, `ITEMATTRIBUTES`, `STOREID`, `SESSIONID`, `BUYERID`)
								SELECT `ITEMID`, `QUANTITY`, `ITEMATTRIBUTES`, `STOREID`, `SESSIONID`, `BUYERID`
               			FROM `cart_tbl` 
               			WHERE `STOREID` = $pStoreID
						AND BUYERID = $buyerID";
	/*echo $sql;
	exit;*/
	
	$this->db->setQuery(htmlentities($sql), 'orderIsConfirmed');
	if($this->showQuery) 
		$this->printQuery();
	$this->db->executeQuery($sql);
	
	//Now updating orderdetail by putting Ordernumber in it.
	$sql = "UPDATE `orderdetail_tbl`
						SET `ORDERNUMBER` = '$pOrderNumber',
							 `SESSIONID` = 'CHECKED OUT'
						WHERE `STOREID` = '$pStoreID'
						AND BUYERID = '$buyerID'";
						
	$this->db->setQuery(htmlentities($sql), 'orderIsConfirmed');
	$this->db->executeQuery($sql);
	
	//Now Setting up the isPaid field of orders_tbl to 1.
	$sql = "UPDATE `orders_tbl`
						SET `ISPAID` = 1,
							`ORDERSTATUS` = 'PAID'
						WHERE ORDERNUMBER = '$pOrderNumber'";
						
	$this->db->setQuery(htmlentities($sql), 'orderIsConfirmed');
	if($this->showQuery) 
		$this->printQuery();
	$this->db->executeQuery($sql);
	
	
	//And finally DELETING the cart
	$sql = "DELETE FROM `cart_tbl`
			  			WHERE `BUYERID` = '$buyerID'
						AND `STOREID` = $pStoreID";
						
	/*echo 'store::orderIsConfirmed:: '.$sql;
	exit;*/
	
	$this->db->setQuery(htmlentities($sql), 'orderIsConfirmed');
	if($this->showQuery) 
		$this->printQuery();
	$this->db->executeQuery($sql);
	
	//Updating Store Rent if it is Per Sale based
	$fee = $this->getSingleData('admin_tbl', 'PERSALEFEE', "EMAIL='admin@onlinepaktrade.com'");
	
	$fee = $pAmountWithoutShipping * ($fee / 100);			// GETTING % OF SALE

	if($fee != 0.00):
			//Insert Fee Per sale
			$f = 'STOREID;FEEPAIDFOR;FEEAMOUNT;POSTEDON';
			$v = "$pStoreID;'SALE CHARGES-$pOrderNumber';$fee;NOW()";
			$this->insertTable('rentledger_tbl', $f, $v);
	endif;
	
}


public function rentPaid($pStoreID, $pMonth, $pAmount)
{	
	//print_r($pArrItem);
	//echo '<br />item in cart ' .count($pArrItem).'<br />';
	$dt = date('Y-m-d');
	//$pMonth = '01-'.$pMonth;
	
	$field = 'STOREID;MONTHNAME;AMOUNT;PAIDON';
	$values = $pStoreID.';'.mysql_Date($pMonth).';'.$pAmount.';'.CN_S($dt);
	
	$sql = $this->QM_insert('rentreceived_tbl', $field, $values);
	
	$this->db->setQuery(htmlentities($sql), 'rentPaid');
	if($this->showQuery) 
		$this->printQuery();
	$this->db->executeQuery($sql);
	
	//Updateing the members_tbl
	$this->updateTable('members_tbl', 'ACCOUNTBALANCE;RENTSTATUS;RENTPAIDON', "0;'PAID';NOW()",'ID', $pStoreID);

	
}


private function updateStock($pArrItem)
{	
	//print_r($pArrItem);
	//echo '<br />item in cart ' .count($pArrItem).'<br />';
	for($i=0; $i<count($pArrItem); $i++)
	{
		$sql= "UPDATE `item_tbl`
					SET `QUANTITY` = (`QUANTITY` - ".$pArrItem[$i][QUANTITY].")
					WHERE `ID` = ".$pArrItem[$i][ITEMID];
	
		//echo $sql.'<br />';
		//exit;
		$this->db->setQuery(htmlentities($sql), 'updateStock');
		if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery($sql);
		
	}
	
}

function placeOrder($pStoreID, $pAmount, $pShipping)
{
	$ordernumber = $pStoreID.'-'.time();
	$buyerID = $_COOKIE[memberid];
	$sessionID = session_id();
	
	//Deleting the previous order if any exists.
	$sql = "DELETE FROM `orders_tbl` WHERE BUYERID = $_COOKIE[memberid] AND STOREID = $pStoreID AND ORDERSTATUS = 'PLACED'";
	$this->db->setQuery(htmlentities($sql), 'placeOrder');					
	$this->db->executeQuery($sql);
		
		
	$sql = "INSERT INTO `orders_tbl`
			(ORDERNUMBER, ORDERDATE, ORDERSTATUS, ISPAID, STOREID, BUYERID, SESSIONID, ORDERAMOUNT, SHIPPINGAMOUNT, AMOUNTPAID)
	  		VALUES ('$ordernumber', NOW(), 'PLACED', 0, $pStoreID, $buyerID, '$sessionID', $pAmount, $pShipping,0)";
			
	$this->db->setQuery(htmlentities($sql), 'placeOrder');	
	
	if($this->showQuery) 
			$this->printQuery();
			
		$this->db->executeQuery($sql);
}
	

public function setItemOption($pDA)
{
	$fields =	'ISFEATURED;ISONSALE;ISPRODUCTSHOW;METATAG';
				 
	$itemid = $_COOKIE[lastid];
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_S($pDA[isfeatured]).';
				 '.CN_S($pDA[isonsale]).';
				 '.CN_S($pDA[isproductshow]).';
				 '.CN_S($pDA[tags]).'';
				 
				 
	$sql = $this->QM_insert("shipping_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'setItemOption');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
	
}


public function newItem($pDA)
{
	
	$rentSystem = $this->getSingleData('rentsystems_tbl', 'PERITEM', "MALLADMIN='$_COOKIE[admin]'");
	if($rentSystem != 0.00)
		$this->updateStoreFeePerItem($pDA[itemquantity]);
	
	
	$fields =	'STOREID,CATEGORYID,SUBCATID,NAME,COST,PRICE,QUANTITY,DETAIL,KEYWORDS,ISFEATURED,ADDEDON';
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($_COOKIE[memberid]).',
				 '.CN_I($pDA[category]).',
				 '.CN_I($pDA[subcategory]).',
				 '.CN_S($pDA[itemname]).',
				 '.CN_N($pDA[itemcost]).',
				 '.CN_N($pDA[itemprice]).',
				 '.CN_I($pDA[itemquantity]).',
				 '.CN_S($pDA[itemdescription]).',
				 '.CN_S($pDA[keywords]).',
				 '.CN_S($pDA[isfeatured]).',
				 NOW()';
				 
	$sql = "INSERT INTO item_tbl ($fields) VALUES ( $values )";
				 
				 
	$this->db->setQuery($sql, 'newItem');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		$expire=time()-3600;	//Deleting
		setcookie("lastid", "", $expire,"/");
		$expire=time()+60*60*24*1;		//for 1 day.
		setcookie("lastid", $this->db->getLastInsertedID(), $expire,"/");
		return true;
	else:
		return false;
	endif;
}

public function updateStoreFeePerItem($pQuantity)
{
	
	$perItemFee = $this->getSingleData('rentsystems_tbl', 'PERITEM', "MALLADMIN='$_COOKIE[admin]'");
	$myBalance = $this->getSingleData('members_tbl', 'ACCOUNTBALANCE', 'ID='.$_COOKIE[memberid]);
	
	$myBalance += ($perItemFee * $pQuantity);
	
	$sql = $this->QM_update("members_tbl", 'ACCOUNTBALANCE', $myBalance, 'ID', $_COOKIE[memberid]);

	$this->db->setQuery(htmlentities($sql), 'updateStoreFeePerItem');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function updateStoreFeePerMonth()
{
	
	$rentRate = $this->getSingleData('rentsystems_tbl', 'PERMONTH', "MALLADMIN='$_COOKIE[admin]'");
	
	$perDayRate = ($rentRate / DAYS_IN_MONTH);
	
	$sql = "UPDATE members_tbl SET ACCOUNTBALANCE = (DATEDIFF(NOW(), RENTPAIDON) * $perDayRate)";
																  
		
	$this->db->setQuery($sql, 'updateStoreFeePerMonth');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function updateStoreFeePerSale($sale)
{
	
	$commissionRate = $this->getSingleData('rentsystems_tbl', 'PERSALE', "MALLADMIN='$_COOKIE[admin]'");
	$myBalance = $this->getSingleData('members_tbl', 'ACCOUNTBALANCE', 'ID='.$_COOKIE[memberid]);
	
	$myBalance += $sale;
	
	$sql = $this->QM_update("members_tbl", 'ACCOUNTBALANCE', $myBalance, 'ID', $_COOKIE[memberid]);

	$this->db->setQuery(htmlentities($sql), 'updateStoreFeePerSale');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function newMember($pUserName, $pEmail, $pPassword, $pNewsletter, $pSessionid)
{
	$fields =	'STORENAME;PASSWORD;EMAIL;ISNEWSLETTER;REGISTEREDON;MEMBERTYPE;SELLERPICTURE;SESSIONID';
	$pwd = md5($pPassword);
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_S($pUserName).';
				'.CN_S($pwd).';
				'.CN_S($pEmail).';
				 '.CN_B($pNewsletter).';
				 NOW();
				 '.CN_S('B').';
				 '.CN_S('default.jpg').';
				 '.CN_S($pSessionid).'';
				 
				 
	$sql = $this->QM_insert("members_tbl", $fields, $values);

	$this->db->setQuery($sql, 'newMember');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function updateItem($pDA)
{
	
	$sql = 'UPDATE item_tbl SET 
								CATEGORYID = '.CN_I($pDA[category]).',
								SUBCATID = '.CN_I($pDA[subcategory]).',
								NAME = '.CN_S($pDA[itemname]).',
								PRICE = '.CN_N($pDA[itemprice]).',
								QUANTITY = '.CN_I($pDA[itemquantity]).',
								KEYWORDS  = '.CN_S($pDA[keywords]).',
								ISFEATURED = '.CN_I($pDA[isfeatured]).',
								DETAIL = '.CN_S($pDA[itemdescription]).'
			WHERE ID = '.$pDA[itemid].'';
	
				
				 
	//$sql = $this->QM_update("item_tbl", $fields, $values, 'ID', $pDA[itemid]);

	$this->db->setQuery($sql, 'updateItem');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function newCategory($pDA)
{
	//print_r($pDA);
	$fields =	'STOREID;NAME;ADDEDON';
	$dt = date('Y-m-d');			 
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($_COOKIE[memberid]).';
				 '.CN_S($pDA[categoryname]).';
				 '.CN_S($dt).'';
				 
				 
	$sql = $this->QM_insert("category_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'newCategory');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		unset($_SESSION[lastcatid]);
		$_SESSION[lastcatid] = $this->db->getLastInsertedID();
		return true;
	else:
		return false;
	endif;
}

public function newSubCategory($pDA)
{
	//print_r($pDA);
	$fields =	'CATEGORYID;STOREID;NAME;ADDEDON';
	$dt = date('Y-m-d');			 
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($pDA[catid]).';
				 '.CN_I($_COOKIE[memberid]).';
				 '.CN_S($pDA[subcategoryname]).';
				 '.CN_S($dt).'';
				 
				 
	$sql = $this->QM_insert("subcategory_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'newCategory');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		unset($_SESSION[lastsubcatid]);
		$_SESSION[lastsubcatid] = $this->db->getLastInsertedID();
		return true;
	else:
		return false;
	endif;
}


public function newGlobalCategory($pDA)
{
	//print_r($pDA);
	$fields =	'NAME;ADDEDON';
	$dt = date('Y-m-d');			 
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_S($pDA[newgc]).';
				 '.CN_S($dt).'';
				 
				 
	$sql = $this->QM_insert("globalcategory_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'newGlobalCategory');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function newSubGlobalCategory($pDA)
{
	//print_r($pDA);
	$fields =	'GLOBALCATID;NAME;ADDEDON';
	$dt = date('Y-m-d');			 
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_I($pDA[gcid]).';
				 '.CN_S($pDA[newgsc]).';
				 '.CN_S($dt).'';
				 
				 
	$sql = $this->QM_insert("subglobalcategory_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'newSubGlobalCategory');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function setAdminRent($pRentSys, $pRate)
{
	//print_r($pDA);
	$fields =	'RENTSYSTEM;RENTRATE;RENTUPDATEDON';
	$dt = date('Y-m-d');			 
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_S($pRentSys).';
				 '.CN_N($pRate).';
				 '.CN_S($dt).'';
				 
				 
	$sql = $this->QM_update("admin_tbl", $fields, $values, 'EMAIL', "'".$_COOKIE[admin]."'");

	$this->db->setQuery(htmlentities($sql), 'setAdminRent');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

/*public function newMember($pDA)			//DA = Data Array
{

	$this->checkInvitation($pDA[invite_code]);
	
	//exit;
	
	$fields =	'USERNAME;PASSWORD;FIRSTNAME;SURNAME;EMAIL;BIRTHDATE;GENDER;STATUS;HOROSCOP;
				 HOUSENO;STREETNO;COUNTRY;HEIGHT;WEIGHT;EYECOLOR;HAIRCOLOR;RELIGION;ANCESTRY;
				 SMOKING;EDUCATION;PROFESSION;LANGUAGE;INTERESTS;DREAMS;FEARS;MOTTO;ISNEWSLETTER;
				 SIGNEDUPDATE;SESSIONID;INVITEDBY;ISAUTHORIZED';
				 
				 
				 //ref
				 //CN_P = CheckNull and Password Encruption using md5
	$values =	''.CN_S($pDA[username]).';
				 '.CN_P($pDA[password]).';
				 '.CN_S($pDA[firstname]).';
				 '.CN_S($pDA[surname]).';
				 '.CN_S($pDA[email]).';
				 '.CN_S($pDA[birthdate3].'-'.$pDA[birthdate2].'-'.$pDA[birthdate1]).';
				 '.CN_S($pDA[gender]).';
				 '.CN_S($pDA[status]).';
				 '.CN_S($pDA[horoscop]).';
				 '.CN_S($pDA[houseno]).';
				 '.CN_S($pDA[streetno]).';
				 '.CN_S($pDA[country]).';
				 '.CN_N($pDA[height]).';
				 '.CN_N($pDA[weight]).';
				 '.CN_S($pDA[eyecolor]).';
				 '.CN_S($pDA[haircolor]).';
				 '.CN_S($pDA[religion]).';
				 '.CN_S($pDA[ancestry]).';
				 '.CN_S($pDA[smoking]).';
				 '.CN_S($pDA[education]).';
				 '.CN_S($pDA[profession]).';
				 '.CN_S($pDA[language]).';
				 '.CN_S($pDA[interests]).';
				 '.CN_S($pDA[dreams]).';
				 '.CN_S($pDA[fears]).';
				 '.CN_S($pDA[motto]).';
				 '.CN_B($pDA[newsletter]).';
				 '.CN_S(date('y-m-d')).';
				 '.CN_S(session_id()).';
				 '.CN_I($this->invitedBy).';
				 '.CN_B($this->isAuthorized).'';
				 
				 
	$sql = $this->QM_insert("members_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'newMember');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery())
		return true;
	else
		return false;
			
}
*/


public function updateProfile($pField, $pValue, $pKeyField, $pKeyValue)	//$Field;Value style
{
	$sql = $this->QM_update("members_tbl", $pField, $pValue, $pKeyField, $pKeyValue);

	$this->db->setQuery(htmlentities($sql), 'updateProfile');
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}


public function updateOrderAttribute($pCartID, $pNew, $pOld, $pAttName)	
{
	$att = $this->getSingleData("cart_tbl", 'ITEMATTRIBUTES', 'ID='.$pCartID);
	
	if($pOld == '')
	{
		$newAtt = $pAttName.':'.$pNew.';';
		$att .= $newAtt;
	}
	else
	{
		$att = str_replace($pOld, $pNew, $att);
	}
	
	//$sql = $this->QM_update("cart_tbl", 'ITEMATTRIBUTES', CN_S($newAtt), 'ID', $pCartID);
	$sql = "UPDATE cart_tbl SET ITEMATTRIBUTES = '".$att."' WHERE ID = $pCartID";

	/*echo $sql;
	exit;*/
	$this->db->setQuery(htmlentities($sql), 'updateOrderAttribute');
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}

public function updateTable($pTable, $pField, $pValue, $pKeyField, $pKeyValue)	//$Field;Value style
{
	//echo '<br />update Table '.$pValue.'<br />';
	$sql = $this->QM_update($pTable, $pField, $pValue, $pKeyField, $pKeyValue);

	$this->db->setQuery($sql, 'updateTable');
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}

public function updateTable_textarea($pTable, $pField, $pValue, $pKeyField, $pKeyValue)	//$Field;Value style
{
	//echo '<br />update Table '.$pValue.'<br />';
	$sql = $this->QM_update_textarea($pTable, $pField, $pValue, $pKeyField, $pKeyValue);

	$this->db->setQuery($sql, 'updateTable');
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}

public function insertTable($pTable, $pField, $pValue)	//$Field;Value style
{
	$sql = $this->QM_insert($pTable, $pField, $pValue);

	$this->db->setQuery($sql, 'insertTable');
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}

public function insertTable_textarea($pTable, $pField, $pValue)	//$Field;Value style
{
	$sql = $this->QM_insert_textarea($pTable, $pField, $pValue);

	$this->db->setQuery($sql, 'insertTable');
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}

public function XTable($pTable, $pField, $pValue)	//$Field;Value style
{
	$sql = $this->QM_delete($pTable, $pField, $pValue);

	$this->db->setQuery(htmlentities($sql), 'XTable '.$pTable);
		
	if($this->showQuery) 
		$this->printQuery();
			
	if($this->db->executeQuery())
		return true;
	else
		return false;

}

public function userConfirmedByEmail($pToken)
{
	$sql = $this->QM_update("members_tbl","SESSIONID", CN_S('ACTIVATED'), "SESSIONID", CN_S($pToken));

	$this->db->setQuery(htmlentities($sql), 'userConfirmedByEmail');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();

}

public function resetPassword($pPassword, $pEmail)
{
	$sql = $this->QM_update("members_tbl","PASSWORD", CN_P($pPassword), "EMAIL", CN_S($pEmail));

	$this->db->setQuery(htmlentities($sql), 'userConfirmedByEmail');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();
	/*echo 'effected rows '.$this->db->affected_rows();
	exit;*/
	
	if($this->db->affected_rows() == 0)		//Checking whether this email exists or not
	{
		$result = false;
	}
	else
	{
		$result = true;
	}
		
	return $result;
	

}


public function deleteUser($pID)
{
	$sql = $this->QM_delete("user_tbl","ID", "$pID");

	$this->db->setQuery(htmlentities($sql), 'deleteUser');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();

}

//SETS========================================================================================================================SETS

//DELETE ====================================================================================================================DELETE
public function XCategory($pDA)
{
	$fields =	'ID';
	$values =	''.CN_I($pDA[categoryID]).'';
				 
				 
	$sql = $this->QM_delete("category_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'XCategory');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function XShipping($pShipID)
{
	$fields =	'ID';
	$values =	''.CN_I($pShipID).'';
				 
				 
	$sql = $this->QM_delete("shipping_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'XShipping');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function XAttribute($pAttID)
{
	$fields =	'ID';
	$values =	''.CN_I($pAttID).'';
				 
				 
	$sql = $this->QM_delete("itemattributes_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'XAttribute');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function XItemFromCart($cartid)
{
	$fields =	'ID';
	$values =	$cartid;
				 
				 
	$sql = $this->QM_delete("cart_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'XItemFromCart');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function XItemFromFavorite($pDA)
{
	$fields =	'ID';
	$values =	''.CN_I($pDA[favid]).'';
				 
				 
	$sql = $this->QM_delete("favorites_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'XItemFromFavorite');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}


public function XSubCategory($pDA)
{
	$fields =	'ID';
	$values =	''.CN_I($pDA[subcategoryid]).'';
				 
				 
	$sql = $this->QM_delete("subcategory_tbl", $fields, $values);

	$this->db->setQuery(htmlentities($sql), 'XSubCategory');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function XMail($pID, $pType)		//Type: Reader or Sender
{
	$sql = $this->QM_update("mails_tbl",$pType, 1, "ID", "$pID");

	$this->db->setQuery(htmlentities($sql), 'XMail');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();

}


public function XItem($pDA)
{
	$itemID =	''.CN_I($pDA[itemID]).'';
	
	//Deleting shipping of this item
	$sql = $this->QM_delete("shipping_tbl", 'ITEMID', $itemID);
	$this->db->setQuery(htmlentities($sql), 'XItem');
		
	if($this->showQuery) 
		$this->printQuery();
	
	$this->db->executeQuery();
				 
	$sql = $this->QM_delete("item_tbl", 'ID', $itemID);
	$this->db->setQuery(htmlentities($sql), 'XItem');
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery()):
		return true;
	else:
		return false;
	endif;
}

public function XData($pTableName, $pField, $pValue)		//General Delete function
{
	$sql = $this->QM_delete($pTableName, $pField, $pValue);
	$this->db->setQuery(htmlentities($sql), 'XData from Table ',$pTableName);
		
	if($this->showQuery) 
		$this->printQuery();
	
	$this->db->executeQuery();
}

public function Run($sql, $callFrom = 'Run')		//General Delete function
{

	$this->db->setQuery($sql, $callFrom);
		
	if($this->showQuery) 
		$this->printQuery();
	
	if($this->db->executeQuery())
		return true;
	else
		return false;
}

//DELETE ====================================================================================================================DELETE

//PRINTS========================================================================================================================PRINTS

	public function printQuery()
	{
		echo '<br> The query is being called from '.$this->db->queryFiredFrom.'<br>';
		echo 'Query = '.$this->db->query.'<br>';
		
		if($this->exitScript) 
		{
			echo '------- Exiting the script --------';
			exit;
		}
			
	}
//PRINTS========================================================================================================================PRINTS

function QM_insert($pTable,$pField,$pValue){

	$sql = "";

	$tmpField=explode(";",$pField);
	$tmpValue=explode(";",$pValue);
	
	$sql = "INSERT INTO `".$pTable."` (`";
	
	for($i=0; $i<count($tmpField); $i++){
	
		$sql .= trim($tmpField[$i])."`,`";
	
	}
	
	$sql = substr($sql, 0, -3);			//CLIPPING THE LAST ,

	$sql .= "`) VALUES (";
	
	for($k=0; $k<count($tmpValue); $k++){
	
		$sql .= $tmpValue[$k].",";
	
	}
	
	$sql = substr($sql, 0, -1);			//CLIPPING THE LAST ,
	
	$sql .= ")";
	

	return $sql;
}

function QM_insert_textarea($pTable,$pField,$pValue){

	$sql = "";

	$tmpField=explode("|",$pField);
	$tmpValue=explode("|",$pValue);
	
	$sql = "INSERT INTO `".$pTable."` (`";
	
	for($i=0; $i<count($tmpField); $i++){
	
		$sql .= trim($tmpField[$i])."`,`";
	
	}
	
	$sql = substr($sql, 0, -3);			//CLIPPING THE LAST ,

	$sql .= "`) VALUES (";
	
	for($k=0; $k<count($tmpValue); $k++){
	
		$sql .= $tmpValue[$k].",";
	
	}
	
	$sql = substr($sql, 0, -1);			//CLIPPING THE LAST ,
	
	$sql .= ")";
	

	return $sql;
}



function QM_delete($pTable,$pField,$pValue){

	$sql = "";
	
	$tmpField=explode(";",$pField);
	$tmpValue=explode(";",$pValue);
	
	$sql = "DELETE FROM `".$pTable."` WHERE `";
	
	 for($i=0; $i<count($tmpField); $i++){
	
		$sql .= trim($tmpField[$i])."` = ".$tmpValue[$i]." AND `";
	
	}
	
	$sql = substr($sql, 0, -5);			//CLIPPING THE LAST ,
	
	return $sql;
	
}


function QM_update($pTable,$pField,$pValue,$pKey,$pKeyVal){
	$sql = "";
	$tmpField=explode(";",$pField);
	$tmpValue=explode(";",$pValue);
	$tmpKey=explode(";",$pKey);
	$tmpKeyVal=explode(";",$pKeyVal);
	
	$sql = "UPDATE `".$pTable."` SET `";
	
	for($i=0; $i<count($tmpField); $i++){
	
		$sql .= trim($tmpField[$i])."` = ".$tmpValue[$i].",`";
	
	}
	
	$sql = substr($sql, 0, -2);			//CLIPPING THE LAST ,
	$sql .= " WHERE `";
	
	for($i=0; $i<count($tmpKey); $i++){
	
		$sql .= $tmpKey[$i]."` = ".$tmpKeyVal[$i]." AND `";
	
	}
	
	$sql = substr($sql, 0, -5);			//CLIPPING THE LAST ' AND '
	
	return $sql;	
}


function QM_update_textarea($pTable,$pField,$pValue,$pKey,$pKeyVal){
	$sql = "";
	$tmpField=explode("|",$pField);
	$tmpValue=explode("|",$pValue);
	$tmpKey=explode("|",$pKey);
	$tmpKeyVal=explode("|",$pKeyVal);
	
	$sql = "UPDATE `".$pTable."` SET `";
	
	for($i=0; $i<count($tmpField); $i++){
	
		$sql .= trim($tmpField[$i])."` = ".$tmpValue[$i].",`";
	
	}
	
	$sql = substr($sql, 0, -2);			//CLIPPING THE LAST ,
	$sql .= " WHERE `";
	
	for($i=0; $i<count($tmpKey); $i++){
	
		$sql .= $tmpKey[$i]."` = ".$tmpKeyVal[$i]." AND `";
	
	}
	
	$sql = substr($sql, 0, -5);			//CLIPPING THE LAST ' AND '
	
	return $sql;	
}

function QM_select($pTable,$pField,$pKey,$pKeyVal)
{
	$tmpField=explode(";",$pField);
	$tmpValue=explode(";",$pValue);
	$tmpKey=explode(";",$pKey);
	$tmpKeyVal=explode(";",$pKeyVal);
	
	if($pField != '*')
	{
		$sql = "SELECT `";
		for($i=0; $i<count($tmpField); $i++){
			$sql .= trim($tmpField[$i])."`,`";
		}
	}
	else
	{
		$sql = "SELECT *,,";
	}
	
	$sql = substr($sql, 0, -2);			//CLIPPING THE LAST ,
	
	$sql .= " FROM `".$pTable."` WHERE ";
	
	for($i=0; $i<count($tmpKey); $i++){
	
		$sql .= $tmpKey[$i]." = ".$tmpKeyVal[$i]." AND ";
	
	}
	
	$sql = substr($sql, 0, -5);			//CLIPPING THE LAST ' AND '
	
	return $sql;
}
// Query Maker Function =======================================================================================================Query Maker Function


// Query Maker Function =======================================================================================================Query Maker Function


//===================================== Local functions ================================
function checkInvitation($pCode){
	$data = $this->getSingleData('authorize_tbl', 'INVITEDBY', "AUTHORIZECODE='$pCode'");
	
	if($data != '')
	{
		$this->invitedBy = $data;
		$this->isAuthorized = true;
	}else
	{
		$this->isAuthorized = false;
		$this->invitedBy = null;
	}
	//print_r($data);
	
}

//============================ Rent Processing ===========================
public function getNewSellers($pMonth = null)
{
	$sql = "SELECT ID, REGISTEREDON FROM members_tbl 
			WHERE RENTSTATUS = 'NEW'";
	$this->db->setQuery(htmlentities($sql), 'getNewSellers');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();
	$tempArray = array();
		while ($row = $this->db->fetch_array()) {
        	$tempArray[] = $row;
		}
		
		//print_r($tempArray);
		
		return $tempArray;
}

function getRentDays($pStoreID)
{
	$sql = "SELECT DATEDIFF(CURDATE(), RENTPAIDON) AS DAYS FROM members_tbl 
			WHERE ID = $pStoreID";
			
	$this->db->setQuery(htmlentities($sql), 'getNewSellers');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();
	
	$row = $this->db->fetch_array();
	
	return $row[DAYS];
}

public function makeRentBill_monthly($pRent, $pMonth, $pYear)
{
	$makeDate = $pYear.'-'.$pMonth.'-01';
	$sql = "UPDATE members_tbl SET ACCOUNTBALANCE = (ACCOUNTBALANCE+$pRent), RENTMONTH = '$makeDate', RENTSTATUS = 'DUE'
			WHERE RENTSTATUS != 'NEW'";
			
	$this->db->setQuery(htmlentities($sql), 'makeRentBill');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();
}

public function makeRentBill_peritem($pMonth, $pYear)
{
	$makeDate = $pYear.'-'.$pMonth.'-01';
	$sql = "UPDATE members_tbl SET RENTMONTH = '$makeDate', RENTSTATUS = 'DUE'";
			
	$this->db->setQuery(htmlentities($sql), 'makeRentBill_peritem');
		
	if($this->showQuery) 
		$this->printQuery();
			
	$this->db->executeQuery();
}

public function closeConnection()
{
	$this->db->close();
}

// Some Testing ===========================
public function sendMail($pMessage)
{
	mail('najeeb.ahmd@gmail.com','Hello',$pMessage);
}

}
?>